package com.tuanzi.utils;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import java.io.IOException;
import java.util.*;

public class GetWeather {

    //创建一个集合，用来保存所有的温度，用来算出最近天气的温度
    private static List tempTureList = new LinkedList();

    public GetWeather() {
    }

    public static List search() throws IOException {
        String cityCode = "101130101";
        String url = (new StringBuilder()).append("http://www.weather.com.cn/weather/").append(cityCode).append(".shtml").toString();
        List lweatherTempture = new LinkedList();
        try {
            Document doc = Jsoup.connect(url).get();
            Elements content = doc.getElementsByClass("t clearfix");
            for(Iterator iterator = content.iterator(); iterator.hasNext();) {
                Element e = (Element)iterator.next();
                Document conDoc = Jsoup.parse(e.toString());
                Elements sky = content.select("li[class^=sky skyid lv]");
                Iterator iterator1 = sky.iterator();
                while(iterator1.hasNext()) {
                    Element e1 = (Element)iterator1.next();
                    Elements weatherTempture = e1.select("p[class=tem]");
                    lweatherTempture.add(weatherTempture.text());
                }
            }

        } catch(Exception e) {
            e.printStackTrace();
        }


        return lweatherTempture;
    }

    /**
     * 获取未来七天的平均温度
     */
    public static List<Float> GetWeatherTemperature() throws IOException {
        String s = new Date().toString().split(" ")[3].split(":")[0];
        float aFloat = Float.parseFloat(s);

        // 获取每天的平均温度
        List<Float> temperatureList = new LinkedList<>();

        // 获取当天的天气
        int num = 0;
        List search = GetWeather.search();
        for (Object tem : search) {
            String t = tem.toString().replace("℃", " ");
            t.replace(" ","");
            if(num == 0 && aFloat >= 18){
                temperatureList.add(Float.parseFloat(t));
                num++;
                continue;
            }
            float v = Float.parseFloat(t.split("/")[0]);
            float x = Float.parseFloat(t.split("/")[1]);
            temperatureList.add((v+x)/2);
        }

        return temperatureList;
    }



}
